#include "MyFrame.h"
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPainter>

MyFrame::MyFrame(QWidget *parent)
    : QFrame(parent)
{

}

void MyFrame::mousePressEvent(QMouseEvent *event)
{
    QVector<QPoint> line;
    line.push_back(event->pos());
    lines.push_back(line);
    this->update();
}

void MyFrame::mouseMoveEvent(QMouseEvent *event)
{
    //获取最后一个对象
    QVector<QPoint> &line = *(lines.end() - 1);
    line.push_back(event->pos());
    this->update();
}
void MyFrame::mouseReleaseEvent(QMouseEvent *event)
{
    //获取最后一个对象
    QVector<QPoint> &line = *(lines.end() - 1);
    line.push_back(event->pos());
    this->update();
}

void MyFrame::paintEvent(QPaintEvent *)
{
    //绘制
    QPainter painter(this);


    //绘制多条线段
    for(QVector<QVector<QPoint> >::iterator it = lines.begin();
        it != lines.end(); it++){
        this->paintLine(painter, *it);
    }

}

void MyFrame::paintLine(QPainter& painter,
               const QVector<QPoint>& line)
{
    if(line.size() < 2){
        return ;
    }

    for(QVector<QPoint>::const_iterator it = line.begin();
        it != line.end() - 1; it++){
        painter.drawLine(*it, *(it + 1));
    }
}
